<template>
  <PageView>
    <template slot="headerContent">
      <div class="hostPageHeader">
        <span class="title">主机管理</span>
      </div>
    </template>
    <template slot="extra">
      <a-button icon="code" type="primary" @click="openTerminal">
        Web 终端
      </a-button>
    </template>
    <a-row :gutter="12">
      <a-col :span="6">
        <a-card :bordered="false" title="分组列表">
          <a-tooltip title='排版模式下，可通过拖拽分组实现快速排序。' slot="extra">
            <a-switch
              :checked="draggable"
              @change="setDraggable"
              checkedChildren="排版"
              unCheckedChildren="浏览"/>
            <a-icon type="question-circle" style="margin-left: 8px;color: #999999"/>
          </a-tooltip>
          <a-dropdown
            :visible="visible"
            :trigger="['contextmenu']"
            @visibleChange="setVisible"
          >
            <a-menu slot="overlay" @click=setVisible(false) style="width: 150px">
              <a-menu-item key="0" @click="handleAdd('root')">
                <a-icon type="folder"/>
                新建根分组
              </a-menu-item>
              <a-menu-item key="1" @click="handleAdd">
                <a-icon type="folder-add"/>
                新建子分组
              </a-menu-item>
              <a-menu-item key="2" @click="handleAdd('edit')">
                <a-icon type="edit"/>
                重命名
              </a-menu-item>
              <a-menu-divider/>
              <a-menu-item key="3">
                <a-icon type="folder"/>
                添加至分组
              </a-menu-item>
              <a-menu-item key="4">
                <a-icon type="folder"/>
                移动至分组
              </a-menu-item>
              <a-menu-divider/>
              <a-menu-item key="5">
                <a-icon type="folder"/>
                删除主机
              </a-menu-item>
              <a-menu-item key="6" @click="handleRemove"><span style="color: red"><a-icon type="delete"/>删除此分组</span>
              </a-menu-item>
            </a-menu>
            <a-directory-tree
              :treeData="treeData"
              :draggable="draggable"
              @rightClick="handleRightClick"
              @select="handleClick"
              @drop="onDrop">
            </a-directory-tree>
          </a-dropdown>
        </a-card>
      </a-col>
      <a-col :span="18">
        <a-card :bordered="false">
          <s-table
            ref="table"
            :columns="columns"
            :data="loadData"
            :rowKey="(record) => record.id"
          >
            <template slot="operator">
              <a-row>
                <a-col :md="12" :sm="24">
                  <a-input-search placeholder="输入检索" allow-clear style="width: 250px" @search="onSearch"/>
                </a-col>
                <a-col :md="12" :sm="24" class="table-title-right">
                  <a-dropdown>
                    <a-menu slot="overlay">
                      <a-menu-item key="form" @click="$refs.Form.open()">
                        <a-space>
                          <a-icon type="edit" style="font-size: 16px;margin-right: 4px;color: #1890ff"/>
                          <span>新建主机</span>
                        </a-space>
                      </a-menu-item>
                      <a-menu-item key="excel" @click="$refs.importForm.open()">
                        <a-space>
                          <a-avatar
                            shape="square"
                            size="small"
                            :src="icons.excel"
                          />
                          <span>Excel</span>
                        </a-space>
                      </a-menu-item>
                    </a-menu>
                    <a-button icon="plus" type="primary">
                      新建
                      <a-icon type="down"/>
                    </a-button>
                  </a-dropdown>
                </a-col>
              </a-row>
            </template>
            <span slot="action" slot-scope="text, record">
            <a v-if="hasPerm('host:edit')" @click="$refs.Form.open(record)">编辑</a>
            <a-divider type="vertical" v-if="hasPerm('host:edit') & hasPerm('host:delete')"/>
            <a-popconfirm v-if="hasPerm('host:delete')" placement="topRight" title="确认删除？"
                          @confirm="() => hostDelete(record.id)">
              <a style="color: red">删除</a>
            </a-popconfirm>
          </span>
          </s-table>
          <s-form ref="Form" @ok="handleOk"/>
          <ImportForm ref="importForm" @ok="handleOk"></ImportForm>
        </a-card>
      </a-col>
    </a-row>
  </PageView>
</template>
<script>
  import { PageView } from '@/layouts'
  import { STable, XCard } from '@/components'
  import sForm from './Form'
  import ImportForm from '@/views/system/host/ImportForm'
  import { Empty } from 'ant-design-vue'
  import * as api from '@/api/main/host'
  import * as groupApi from '@/api/main/group'
  import icons from './icons'
  import style from './index.less'


  export default {
    components: {
      PageView,
      XCard,
      STable,
      sForm,
      ImportForm
    },
    data() {
      return {
        queryParam: {},
        columns: [
          {
            title: '主机名称',
            dataIndex: 'hostname'
          },
          {
            title: '连接地址',
            dataIndex: 'ip'
          },
          {
            title: '端口',
            dataIndex: 'port'
          }, {
            title: '备注',
            dataIndex: 'desc'
          }
        ],
        visible: false,
        draggable: false,
        icons: icons,
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return api.getPage(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        treeData: [],
        groupForm: {
          name: '',
          parent: ''
        },
        group: {},
        bakTreeData: '',
        action: '',
        sexDictTypeDropDown: [],
        statusDictTypeDropDown: [],
        simpleImage: Empty.PRESENTED_IMAGE_SIMPLE
      }
    },
    created() {
      this.getGroupTree()
      if (this.hasPerm('host:edit') || this.hasPerm('host:delete') || this.hasPerm('host:console')) {
        this.columns.push({
          title: '操作',
          width: '300px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        })
      }
    },
    methods: {
      getGroupTree() {
        groupApi.getList(Object.assign(this.queryParam)).then(res => {
          this.treeData = res.data.data
        })
      },
      handleRightClick(v) {
        if (this.hasPerm('host:edit')) {
          this.group = v.node
          this.setVisible(true)
        }
      },
      onSearch(val) {
        this.queryParam.search = val
        this.$refs.table.refresh()
      },
      setVisible(checked) {
        this.visible = checked
      },
      setDraggable(checked) {
        this.draggable = checked
      },
      handleRemove() {
        groupApi.deleteObj(this.group.value).then(res => {
          if (res.success) {
            this.$message.success('删除成功！')
            this.group = ''
            this.getGroupTree()
          } else {
            this.$message.error('删除失败' + res.message)
          }
        })
      },
      handleAdd(value) {
        if (value === 'root') {
          this.group = ''
        } else if (value === 'edit') {
          this.action = value
          this.groupForm.name = this.group.title
          this.groupForm.id = this.group.value
        } else {
          this.groupForm.parent = this.group.value
        }
        this.$confirm({
          title: this.action === 'edit' ? '重命名' : '添加主机节点分组',
          icon: 'info-circle',
          content: this.addGroupForm,
          onOk: this.action === 'edit' ? this.editGroup : this.addGroup,
          onCancel() {
            console.log('Cancel')
          }
        })
      },
      addGroupForm() {
        return (
          <div>
            <a-form-item label="主机节点">
              <a-input v-model={this.groupForm.name}/>
            </a-form-item>
          </div>
        )
      },
      editGroup() {
        groupApi.updateObj({ id: this.groupForm.id, name: this.groupForm.name }).then(res => {
          if (res.success) {
            this.$message.success('重命名成功！')
          } else {
            this.$message.error('重命名失败' + res.message)
          }
          this.groupForm.name = ''
          this.action = ''
          this.getGroupTree()
        })
      },
      addGroup() {
        groupApi.addObj({ name: this.groupForm.name, parent: this.groupForm.parent }).then(res => {
          if (res.success) {
            this.$message.success('新增分组成功！')
          } else {
            this.$message.error('新增分组成功' + res.message)
          }
          this.groupForm.name = ''
          this.action = ''
          this.getGroupTree()
        })
      },
      onDrop(info) {
        const dropKey = info.node.eventKey // 目标的key
        const dragKey = info.dragNode.eventKey // 自己的key
        const dropPos = info.node.pos.split('-')
        const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
        const params = { id: dragKey, d_id: dropKey, action: dropPosition } // 传给后端参数
        groupApi.updatePartObj(params).then(res => {
          if (res.success) {
            this.getGroupTree()
          } else {
            return false
          }
        })
      },
      hostDelete(id) {
        api.deleteObj(id).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        })
      },
      // 连接主机
      Console(id) {
        let link = this.$router.resolve({
          path: `/ssh/${id}`
        })
        window.open(link.href, '_blank')
      },
      openTerminal() {
        window.open('/test_ssh')
      },
      handleClick(e) {
        this.queryParam = {
          group: e.toString()
        }
        this.$refs.table.refresh()
      },
      handleOk() {
        this.$refs.table.refresh()
        this.getGroupTree()
      }
    }
  }
</script>
<style lang="less">
</style>